var express = require('express');
var path = require('path');
//var logger = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bodyParser = require('body-parser');
var lyby = require('./util.js');

//zxq add begin
var hbs = require('./hbs');
//zxq add end

var app = express();
app.all('*', function(req, res, next) {
    //res.header("Access-Control-Allow-Origin", "http://lyby.500px.me:8097");
    //res.header("Access-Control-Allow-Headers", "X-Requested-With");
    //res.header("Access-Control-Allow-Methods","POST,OPTIONS");
    //res.header("X-Powered-By",' 3.2.1')
    if(req.url){
        ///(.*)(.css|.js|.svg|.jpg|.png|.gif)$/.test(req.url)
        //如果有后缀的路径，则加上缓存
        if(path.extname(req.url)){
            res.header("Cache-Control","public, max-age=86400, must-revalidate");
        }
    }
    next();
});

/*log4js begin*/
//var log4js = require('./log4js');
//log4js.use(app);
/*log4js begin*/

global.__basename = __dirname;
global.__hbstplname = __dirname + '/views/tpl';
hbs.registerPartials(__hbstplname);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
//zxq add
app.engine('hbs', hbs.__express);
//hbs.registerPartial('headPartial', __dirname + '/views/tpl/error');


// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//app.use(logger('dev'));
app.use(bodyParser.text({type: 'text/xml'}));//xml的传参转成字符串
app.use(bodyParser.json({
    limit: '50mb'
}));
app.use(bodyParser.urlencoded({ limit: '50mb',extended: false }));
app.use(cookieParser());

global.__timeout = 7776000;
app.use(session({
    secret: '12345',
    name: 'testapp', //这里的name值得是cookie的name，默认cookie的name是：connect.sid
    cookie: {maxAge: __timeout},//设置maxAge是80000ms，即80s后session和相应的cookie失效过期
    resave: false,
    saveUninitialized: true
}));

//加载lessMiddleware模块，这个是开发的时候用的，线上不要，所以放到bin包下面去
// require(path.join(__dirname, 'bin/lessMiddleware')).init(app,'public_shijue');
/*log4js begin*/
// var log4js = require('./log4js');
// log4js.use(app,'shijue');
/*log4js begin*/

app.use(express.static(path.join(__dirname, 'public')));



//app.get("/", function (req, res) {
//  // req.models is a reference to models used above in define()
//  var dd = orm;e
//  req.models.person.find();
//  console.info(2222)
//});
require('./route.js').init(app);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});
//global.__appid = 'wx9d90b4ab0160f168';
//global.__secret = 'd4624c36b6795d1d99dcf0547af5443d';

/*global.__appid = 'wxd60228dbce4cbf67';
global.__secret = '9fc86ed3eefd683e022c03db74905186';
lyby.httpsGetJson('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+__appid+'&secret='+__secret, function (error, data) {
    lyby.httpsGetJson('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+data.access_token+'&type=jsapi',function(e,d){
        console.log(d);
        global.__wxTicket = d;
    });
});*/

module.exports = app;
